import 'package:get/get.dart';
import 'package:raze/lore/glyph/diary_essence.dart';

/// 日志状态管理
/// 全局日志状态，提供日志发布、查询等功能
class DiaryChronicle extends GetxController {
  // 所有日志列表
  final _diaryList = <DiaryEssence>[].obs;

  /// 获取所有日志列表
  List<DiaryEssence> get diaryList => _diaryList;

  @override
  void onInit() {
    super.onInit();
    _initializeDefaultDiaries();
  }

  /// 初始化默认日志数据
  void _initializeDefaultDiaries() {
    final now = DateTime.now();

    // 初始化日志（2条，都是图片类型，用户为admin）
    _diaryList.value = [
      DiaryEssence(
        id: '1',
        userId: '1',
        contentType: 'image',
        media: 'assets/images/diary1.png',
        detail:
            '🌧️ Post-Rain Observation Log\nTime: 4:17 PM · After light rain\nPlace: Forest trail edge\nNotes:\n Leaves shimmer with new light, droplets tracing their veins.\n Moss glows brighter, breathing quietly under the stones.\n A tiny wildflower bends low, heavy with rain pearls — still beautiful. The air smells of soil and renewal.\nReflection: After every rain, the world feels newly born — and so do I.',
        createTime: now.subtract(const Duration(days: 3)),
      ),
      DiaryEssence(
        id: '1',
        userId: '1',
        contentType: 'image',
        media: 'assets/images/diary2.png',
        detail:
            '🌧️ Post-Rain Observation Log\nTime: 6:42 AM · After early morning drizzle\nPlace: Riverside footpath\nNotes:\n The willow leaves tremble softly, each holding a round drop of silver light.\n Grass along the path stands taller, refreshed as if waking from a long sleep.\n A cluster of small seedlings pushes through the damp soil, their green brighter than before.\n The river carries a deeper scent today — cool, earthy, quietly steady.\nReflection: Rain doesn\'t just water the earth; it rewrites the morning. And somehow, it rewrites me too.',
        createTime: now.subtract(const Duration(days: 3)),
      ),
      DiaryEssence(
        id: '1',
        userId: '1',
        contentType: 'image',
        media: 'assets/images/diary3.png',
        detail:
            '🌧️ Post-Rain Observation Log\nTime: 3:09 PM · After a sudden afternoon shower\nPlace: Hillside meadow\nNotes:\n Raindrops cling to the tall grasses, swaying like strings of tiny crystals.\n A faint mist rises from the ground, softening the colors of the distant trees.\n A lone fern unfurls a new frond, still curled and shining with moisture.\n The breeze carries a cool, green scent — part rain, part leaf, part quiet magic.\nReflection: Every rain leaves a softness behind, a gentle reminder that growth often happens in silence.',
        createTime: now.subtract(const Duration(days: 3)),
      ),
    ];
  }

  /// 发布日志
  /// [userId] 发布者用户ID
  /// [contentType] 内容类型：'image' 或 'video'
  /// [media] 媒体路径
  /// [coverImage] 视频封面图（仅视频类型需要）
  /// [detail] 详情文字
  /// 返回创建的日志ID
  String publishDiary({
    required String userId,
    required String contentType,
    required String media,
    String? coverImage,
    required String detail,
  }) {
    final newId = (_diaryList.length + 1).toString();
    final newDiary = DiaryEssence(
      id: newId,
      userId: userId,
      contentType: contentType,
      media: media,
      coverImage: coverImage,
      detail: detail,
      createTime: DateTime.now(),
    );
    _diaryList.add(newDiary);
    return newId;
  }

  /// 根据ID查询日志
  /// [diaryId] 日志ID
  /// 返回日志，不存在返回null
  DiaryEssence? queryDiaryById(String diaryId) {
    return _diaryList.firstWhereOrNull((diary) => diary.id == diaryId);
  }

  /// 获取用户的所有日志列表
  /// [userId] 用户ID
  /// 返回按时间倒序排列的该用户的所有日志列表
  List<DiaryEssence> fetchUserDiaries(String userId) {
    return _diaryList.where((diary) => diary.userId == userId).toList()
      ..sort((a, b) => b.createTime.compareTo(a.createTime));
  }

  /// 获取所有日志列表（按时间倒序排列）
  /// 返回按时间倒序排列的所有日志列表
  List<DiaryEssence> fetchAllDiaries() {
    return List.from(_diaryList)
      ..sort((a, b) => b.createTime.compareTo(a.createTime));
  }

  /// 删除日志
  /// [diaryId] 日志ID
  /// 返回操作结果，成功返回true，失败返回false（日志不存在）
  bool eraseDiaryById(String diaryId) {
    final index = _diaryList.indexWhere((diary) => diary.id == diaryId);
    if (index == -1) {
      return false; // 日志不存在
    }

    // 删除日志
    _diaryList.removeAt(index);

    return true;
  }
}
